<?php
require_once('Account.php');

class User {

    protected $id_user;
    protected $matricule;
    protected $name;
    protected $name_spouse;
    protected $first_name;
    protected $email;
    protected $id_manager;
    protected $id_node;
    protected $id_node_label;
    protected $id_node_type;
    protected $title;
    protected $start_date;
    protected $end_date = NULL;
    protected $id_profile;
    protected $profile;
    protected $id_profile_type; /* 1=Collaborateur - 2=Manageur - 3=Expert RH - 4=Administrateur - 5=Super Administrateur (SIRH Consulting) */
    protected $TreeManagerUser; //tableau des managers sous le user connecté

    /**
     * @var Account
     */
    public $obj_Account;

    public function load($param_id_user, $param_id_compte_client = NULL) {
        try {

            if (!isset($param_id_compte_client)) {
                $query = "SELECT id_compte_client FROM adm_connexion WHERE id_user=:id";
                $data = db_request_select($query, [':id' => $param_id_user]);

                if ($data[0][0] === NULL) {
                    // TODO
                    throw new Exception("Fatal!");
                }

                $param_id_compte_client = $data[0]['id_compte_client'];
                unset($data);
            }

            $this->obj_Account = new Account($param_id_compte_client);

            $data = $this->get_user_data($param_id_user, $this->obj_Account->get_db_name());

            $this->id_user = $param_id_user;
            $this->matricule = $data[0][4];
            $this->name = $data[0][1];
            $this->name_spouse = $data[0][3];
            $this->first_name = $data[0][2];
            $this->email = $data[0][5];
            $this->id_manager = $data[0][6];
            $this->id_node = $data[0][7];
            $this->id_node_label = $data[0][8];
            $this->id_node_type = $data[0][9];
            $this->title = $data[0][10];
            $this->start_date = $data[0][11];
            $this->end_date = $data[0][12];
            $this->id_profile = $data[0][13];
            $this->profile = $data[0][14];
            $this->id_profile_type = $data[0][15];
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // assesseurs
    //============================================================================
    public function get_id_user() {
        return $this->id_user;
    }

    public function get_name() {
        return $this->name;
    }

    public function get_first_name() {
        return $this->first_name;
    }

    public function get_id_profile() {
        return $this->id_profile;
    }

    public function get_profile() {
        return $this->profile;
    }

    public function get_id_node() {
        return $this->id_node;
    }

    // les deux argument doivent être passé ensemble
    public function get_id_profile_type($id_user = NULL, $db_name = NULL) {
        try {
            GLOBAL $REQUEST_052;
            if ($id_user == NULL) {
                return $this->id_profile_type;
            } else {
                $tab_arg = array(':id_user' => $id_user);
                $data = db_request_select($REQUEST_052, $tab_arg, $db_name);
                return (int) $data[0][0];
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function get_id_pwd_user($id_user) {
        try {
            GLOBAL $REQUEST_029;
            $tab_arg = array(':id_user' => $id_user);

            $data = db_request_select($REQUEST_029, $tab_arg, NULL);

            return $data;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // create_user()
    //============================================================================
    public static function db_create($tab_arg_1, $tab_arg_2) {
        GLOBAL $MESSAGE_0019,
        /* $REQUEST_033, */$REQUEST_032, $REQUEST_025;

        /*
         * Obtient le nom de la base de données cible.
         * Le type d'utilisateur "Super administrateur"
         * est habilité sur toutes les bases de données.
         */
        $param_db_name = Account::get_db_name_($tab_arg_1[':id_client_account']);

        //On vérifie que le login n'existe pas déjà
        global $REQUEST_037;
        if (db_request_select($REQUEST_037, [':login' => $tab_arg_1[':login']])[0] !== FALSE)
            throw new SqlCommandException($MESSAGE_0019);

        //On insère dans la base de données SIRH-central les paramètres de connexion
        /* db_request_insert($REQUEST_032, $tab_arg_1, NULL); */

        //On récupère l'id_user du nouveau utilisateur
        /* $data = db_request_select($REQUEST_033, $tab_arg_1, NULL); */
        $tab_arg_2[':id_user'] = /* $data[0][0] */db_request_insert($REQUEST_032, $tab_arg_1, NULL);

        // On crée l'utilisateur dans la base de données du client auquel il appartient
        db_request_insert($REQUEST_025, $tab_arg_2, $param_db_name);
    }

//============================================================================
// update_user()
// Cette fonction permet de mettre à jour les données d'un user. Elle est
// utilisé dans plusieurs contexte:
// Soit un super-administrateur qui renseigne tous les param d'entrées
// Soit un admin qui renseigne que les deux tableaux de param d'entrées (la database étant de facto la sienne)
// Soir un collaborateur qui met simplement à jour ses identifiants de connexion (tab_arg_1 not NULL)
//============================================================================
    public function update_user($id_client_account, $tab_arg_1, $tab_arg_2 = NULL) {
        GLOBAL $REQUEST_035, $REQUEST_036, $REQUEST_038, $MESSAGE_0019;

// On récupère le nom de la base données client ciblé (car en mode super-administrateur on peut sauter d'une base à l'autre)
        $param_db_name = $this->obj_Account->get_db_name($id_client_account);

//=============================================================================
//On vérifie que le login n'existe pas déjà pour un autre user
        $tab_arg_tmp = array(':login' => $tab_arg_1[':login'],
            ':id_user' => $tab_arg_1[':id_user']);

        $data = db_request_select($REQUEST_038, $tab_arg_tmp, NULL);

        if ($data[0][0] == NULL) {
//=============================================================================
//On met à jour dans la base de données SIRH-central les paramètres de connexion (identifiant / pwd)
            db_request_update($REQUEST_035, $tab_arg_1, NULL);

            if ($tab_arg_2 != NULL) {
                //=============================================================================
                // On met à jour l'utilisateur dans la base de données du client auquel il appartient
                db_request_update($REQUEST_036, $tab_arg_2, $param_db_name);
            }
        } else {
            throw new Exception($MESSAGE_0019);
        }
    }

//============================================================================
// delete_user()
//============================================================================
    public function delete_user($id_user, $id_client) {
        GLOBAL $REQUEST_027, $REQUEST_039, $REQUEST_045, $MESSAGE_0021;

        $param_db_name = $this->obj_Account->get_db_name($id_client);

//On vérifie que le collaborateur ne soit pas un manager pour un autre collaborateur
        $tab_arg = array(':id_user' => $id_user);
        $data = db_request_select($REQUEST_027, $tab_arg, $param_db_name);

        if ($data[0][0] == NULL) {
            $tab_arg = array(':id_user' => $id_user);
            // Suppression dans la database du client
            db_request_delete($REQUEST_039, $tab_arg, $param_db_name);
            // Suppression dans la database centrale
            db_request_delete($REQUEST_045, $tab_arg, NULL);
        } else {
            throw new Exception($MESSAGE_0021);
        }
    }

//============================================================================
// get_user_data()
//============================================================================
    public function get_user_data($param_id_user, $param_db_name) {

        GLOBAL $REQUEST_002;
        try {
            $tab_arg = array(':param_id_user' => $param_id_user);

            $data = db_request_select($REQUEST_002, $tab_arg, $param_db_name);

            return $data;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

//============================================================================
// get_all_users_name()
// Récupère id_user + Nom & Prénom pour remplir un <select> 
//============================================================================
    public function get_all_users_name($param_db_name = NULL) {

        GLOBAL $REQUEST_026, $REQUEST_027;

        $data = NULL;
        $tab_arg = array();

        switch ($this->get_id_profile_type()) {
            case PROFILE_COLLABORATEUR: //Collaborateur ??????????????? à clarifier avec SIRH pour le scope
                break;
            case PROFILE_MANAGER: //Manager voit tous les collaborateurs qui l'on comme manager direct
                $tab_arg = array(':id_user' => $this - id_user);
                $data = db_request_select($REQUEST_027, $tab_arg, $this->obj_Account->get_db_name());
                break;
            case PROFILE_EXPERT_RH: //Expert RH ????????????????????? à clarifier avec SIRH pour le scope
                break;
            case PROFILE_ADMINISTRATEUR: //Administrateur voit tout le monde de sa base données passé 
                $data = db_request_select($REQUEST_026, $tab_arg, $this->obj_Account->get_db_name());
                break;
            case PROFILE_SUPER_ADMINISTRATEUR: //Super Administrateur (SIRH Consulting) voit tout le monde d'une base de données passé en paramètre
                $data = db_request_select($REQUEST_026, $tab_arg, ($param_db_name != NULL) ? $param_db_name : $this->obj_Account->get_db_name());
                break;
            default:
                break;
        }

        return $data;
    }

//============================================================================
// get_list_manager()
// renvoie la liste des manageurs (profil manageur mais aussi Expert RH, Administrateur + Sup-Adm)
// suite à une demande SIRH (Attention au effet de bord)
//============================================================================
    public function get_list_manager($param_db_name = NULL) {
        GLOBAL $REQUEST_018;
        return db_request_select($REQUEST_018, array(), ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name);
    }

    public function get_manager_by_name($name_and_firstname, $param_db_name = NULL) {
        global $REQUEST_061;
        return db_request_select($REQUEST_061, [":manager_name_and_firstname" => $name_and_firstname], ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name)[0];
    }

//============================================================================
// get_list_manager_under_user
// fonction qui récupère les managers sous un manager donnée
//============================================================================
    public function get_list_manager_under_user($id_manager, $id_mode = 0) {
        try {
            GLOBAL $REQUEST_051;
            $index = 0;

            $tab_arg = array(':id_manager' => $id_manager);
            $data = db_request_select($REQUEST_051, $tab_arg, $this->obj_Account->get_db_name());

// je copie le premier user dans le tableau résultat
            $this->TreeManagerUser[0][0] = $this->id_user;
            $this->TreeManagerUser[0][1] = $this->name;
            $this->TreeManagerUser[0][2] = $this->first_name;
            $this->TreeManagerUser[0][3] = $this->profile;
            $this->TreeManagerUser[0][4] = $this->id_manager;
            $this->TreeManagerUser[0][5] = $this->id_profile_type;
            $index++;

            if ($data != NULL && $data[0][0] != NULL) {
                for ($inc = 0, $stop = (count($data) - 1); $inc < $stop; $inc++) {
                    if ($id_manager == (int) $data[$inc][4] && $id_manager != (int) $data[$inc][0]) {// S'il est son propre manager
                        $this->TreeManagerUser[$index][0] = $data[$inc][0];
                        $this->TreeManagerUser[$index][1] = $data[$inc][1];
                        $this->TreeManagerUser[$index][2] = $data[$inc][2];
                        $this->TreeManagerUser[$index][3] = $data[$inc][3];
                        $this->TreeManagerUser[$index][4] = $data[$inc][4];
                        $this->TreeManagerUser[$index][5] = $data[$inc][5];
                        $index++;
                        $index = $this->get_list_next_manager_under_user($data[$inc][0], $index);
                    }
                }
            }
            return $this->TreeManagerUser;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    protected function get_list_next_manager_under_user($id_manager, $index) {
        try {
            GLOBAL $REQUEST_051;
            $tab_arg = array(':id_manager' => $id_manager);
            $data = db_request_select($REQUEST_051, $tab_arg, $this->obj_Account->get_db_name());
            $is_found = false;
            if ($data != NULL && $data[0][0] != NULL) {
                for ($inc = 0, $stop = (count($data) - 1); $inc < $stop; $inc++) {
                    //Correction anomalie : boucle manager-manager n-1 -manager
                    $is_found = false;
                    if ($id_manager == (int) $data[$inc][4] && $id_manager != (int) $data[$inc][0]) {// S'il est son propre manager
                        for ($ind = 0, $stopInd = (count($this->TreeManagerUser) - 1); $ind < $stopInd; $ind++) {
                            if ($this->TreeManagerUser[$ind][0] == $data[$inc][0]) {
                                $is_found = true;
                            }
                        }
                        //Si le manager n'est pas déjà dans la liste, on l 'ajoute et on récupère ses collaborateurs
                        if ($is_found == false) {
                            $index = $this->get_list_next_manager_under_user($data[$inc][0], $index);
                            $this->TreeManagerUser[$index][0] = $data[$inc][0];
                            $this->TreeManagerUser[$index][1] = $data[$inc][1];
                            $this->TreeManagerUser[$index][2] = $data[$inc][2];
                            $this->TreeManagerUser[$index][3] = $data[$inc][3];
                            $this->TreeManagerUser[$index][4] = $data[$inc][4];
                            $this->TreeManagerUser[$index][5] = $data[$inc][5];
                            $index++;
                        }
                    }
                }
            }
            return $index;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

//============================================================================
// show_user_data()
//============================================================================

    function Details($twig) {

        // "user_update_login"

        $twig->context['action'] = RenderUrl('users/reset#tab_users');

        $twig->context['hidden'] = [
            'id_user' => $this->id_user,
        ];

        $data = $this->get_user_data($this->id_user, $this->obj_Account->get_db_name());
        $twig->context['user'] = [
            'user_name' => [
                'label' => Strings::LABEL_0019,
                'data' => $data[0][1],
            ],
            'user_firstname' => [
                'label' => Strings::LABEL_0042,
                'data' => $data[0][2]
            ],
            'user_spousename' => [
                'label' => Strings::LABEL_0043,
                'data' => $data[0][3]
            ],
            'user_email' => [
                'label' => Strings::LABEL_0046,
                'data' => $data[0][5]
            ],
            'user_matricule' => [
                'label' => Strings::LABEL_0044,
                'data' => $data[0][4]
            ],
            'user_function' => [
                'label' => Strings::LABEL_0045,
                'data' => $data[0][10]
            ],
            'user_profile' => [
                'label' => Strings::LABEL_0048,
                'data' => $data[0][14]
            ],
            'user_node' => [
                'label' => Strings::LABEL_0050,
                'data' => $data[0][8]
            ],
            'user_date_start_contract' => [
                'label' => Strings::LABEL_0051,
                'data' => strcmp($data[0][11], "00/00/0000") === 0 ? NULL : $data[0][11]
            ],
            'user_date_end_contract' => [
                'label' => Strings::LABEL_0075,
                'data' => strcmp($data[0][12], "00/00/0000") === 0 ? NULL : $data[0][12]
            ],
        ];

        $data_login = $this->get_id_pwd_user($data[0][0]);
        $twig->context['credentials'] = [
            'login_visu_update' => [
                'label' => Strings::LABEL_0005,
                'data' => $data_login[0][0],
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkLogin(this);',
                ],
            ],
            'pwd_visu_update' => [
                'type' => 'password',
                'label' => Strings::LABEL_0006,
                'data' => $data_login[0][1],
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'onblur' => "checkPasswordEx(this,document.getElementById('pwd_visu_update_bis'));",
                ],
            ],
            NULL,
            'pwd_visu_update_bis' => [
                'type' => 'password',
                'label' => Strings::LABEL_0076,
                'data' => $data_login[0][1],
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'onblur' => "checkPasswordEx(this,document.getElementById('pwd_visu_update'));",
                ],
            ],
        ];

        $data_manager = $this->get_user_data($this->id_manager, $this->obj_Account->get_db_name());
        $twig->context['manager'] = [
            'user_manager_name' => [
                'label' => Strings::LABEL_0019,
                'data' => $data_manager[0][1],
            ],
            'user_manager_firstname' => [
                'label' => Strings::LABEL_0042,
                'data' => $data_manager[0][2],
            ],
            'user_manager_profile' => [
                'label' => Strings::LABEL_0048,
                'data' => $data_manager[0][14],
            ],
        ];

        $twig->display('forms/user/details');
    }

    function Create($twig) {

        // "user_creation"
        // 
        // TWIG Context already exists from an 
        // earlier call to function Details($twig)
        // so we just need to adjust the values.
        //
        // For now just clear the context.
        //
        // !! $this->context['exception'] is lost !!

        $this->context = [];

        $twig->context['action'] = RenderUrl('users/create#tab_users');

        if ($this->id_profile_type == PROFILE_SUPER_ADMINISTRATEUR) {

            unset($twig->context['hidden']);

            $twig->context['accounts'] = [
                'client_account_creation' => [
                    'type' => 'select',
                    'label' => Strings::LABEL_0016,
                    'data' => $this->obj_Account->get_list_client(),
                    'selection' => $this->obj_Account->get_id_client_account(),
                    'attributes' => [
                        'onchange' => "ajax_function('" . BASE_WWW . "', '" . AJAX_CONTROLLER . "', ajax_refresh_client_linked_list_creation);",
                    ],
                ],
            ];
        } else {
            $twig->context['hidden'] = [
                'client_account_creation' => $this->obj_Account->get_id_client_account(),
            ];
        }

        $twig->context['user'] = [
            'user_name_creation' => [
                'label' => Strings::LABEL_0019,
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_firstname_creation' => [
                'label' => Strings::LABEL_0042,
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_spousename_creation' => [
                'label' => Strings::LABEL_0043,
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_email_creation' => [
                'label' => Strings::LABEL_0046,
                'attributes' => [
                    'size' => 35,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkEmail(this);',
                ],
            ],
            'user_matricule_creation' => [
                'label' => Strings::LABEL_0044,
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_function_creation' => [
                'label' => Strings::LABEL_0045,
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_profile_creation' => [
                'type' => 'select',
                'label' => Strings::LABEL_0048,
                'data' => $this->get_list_profile(),
            ],
            'user_node_creation' => [
                'type' => 'select',
                'label' => Strings::LABEL_0050,
                'data' => $this->obj_Account->obj_Corporate->get_list_node(),
            ],
            'user_date_start_contract_creation' => [
                'id' => 'datepicker_user_date_start_contract_creation',
                'label' => Strings::LABEL_0051,
                'attributes' => [
                    'size' => 11,
                    'maxlength' => 10,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkDate(this, false);',
                ],
            ],
            'user_date_end_contract_creation' => [
                'id' => 'datepicker_user_date_end_contract_creation',
                'label' => Strings::LABEL_0075,
                'attributes' => [
                    'size' => 11,
                    'maxlength' => 10,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkDate(this, false);',
                ],
            ],
        ];

        $twig->context['credentials'] = [
            'login_creation' => [
                'label' => Strings::LABEL_0005,
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkLogin(this);',
                ],
            ],
            'pwd_creation' => [
                'type' => 'password',
                'label' => Strings::LABEL_0006,
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'onblur' => "checkPasswordEx(this,document.getElementById('pwd_creation_bis'));",
                ],
            ],
            NULL,
            'pwd_creation_bis' => [
                'type' => 'password',
                'label' => Strings::LABEL_0076,
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'onblur' => "checkPasswordEx(this,document.getElementById('pwd_creation'));",
                ],
            ],
        ];

        $data_manager = $this->get_list_manager();
        $twig->context['manager'] = [
            'user_manager_name_creation' => [
                'type' => 'select',
                'label' => Strings::LABEL_0019,
                'data' => $data_manager,
                'attributes' => [
                    'onchange' => "ajax_function('" . BASE_WWW . "', '" . AJAX_CONTROLLER . "', ajax_refresh_manager_form_creation);",
                ],
            ],
            'user_manager_firstname_creation' => [
                'label' => Strings::LABEL_0042,
                'data' => $data_manager[0][2],
                'attributes' => [
                    'size' => 25,
                    'readonly' => true,
                ],
            ],
            'user_manager_profile_creation' => [
                'label' => Strings::LABEL_0048,
                'data' => $data_manager[0][3],
                'attributes' => [
                    'size' => 25,
                    'readonly' => true,
                ],
            ],
        ];

        $twig->context['Export'] = [
            'name' => 'users_export',
            'action' => RenderUrl('users/export#tab_users'),
            'hidden' => [
                'client_account_id' => $this->obj_Account->get_id_client_account(),
            ],
        ];

        $twig->display('forms/user/create');
    }

    function Bulk($twig, $model) {

        // "user_creation_masse"
        // 
        // TWIG Context already exists from an 
        // earlier call to function Create($twig)
        // so we just need to adjust the values.
        //
        // For now just clear the context.
        //
        // !! $this->context['exception'] is lost !!

        $this->context = [];

        $twig->context['action'] = RenderUrl('users/bulk#tab_users');

        if ($this->id_profile_type == PROFILE_SUPER_ADMINISTRATEUR) {

            unset($twig->context['hidden']);

            $twig->context['accounts'] = [
                'client_account_creation' => [
                    'type' => 'select',
                    'label' => Strings::LABEL_0016,
                    'data' => $this->obj_Account->get_list_client(),
                    'selection' => $this->obj_Account->get_id_client_account(),
                ],
            ];
        } else {
            $twig->context['hidden'] = [
                'client_account_creation' => $this->obj_Account->get_id_client_account(),
            ];
        }

        if ($model) {
            foreach ($model as $item) {
                if (isset($item['exception']) && $item['exception'] instanceof RowDataException) {
                    $e = $item['exception'];
                    $previous = $e->getPrevious();
                    if ($previous instanceof ArgumentException)
                        $twig->context['report'][] = sprintf(Strings::MESSAGE_0053, $e->getRow(), $previous->getName(), $previous->GetMessage());
                    else
                        $twig->context['report'][] = sprintf(Strings::MESSAGE_0056, $e->getRow(), $e->GetMessage());
                } else
                    $twig->context['report'][] = sprintf(Strings::MESSAGE_0054, $item['row'][Users::FIELD_NAME], $item['row'][Users::FIELD_FIRSTNAME]);
            }
        }

        $twig->display('forms/user/bulk');
    }

    function Update($twig) {

        // "user_update"
        // 
        // TWIG Context already exists from an 
        // earlier call to function Bulk($twig)
        // so we just need to adjust the values.
        //
        // For now just clear the context.
        //
        // !! $this->context['exception'] is lost !!

        $this->context = [];

        $twig->context['action'] = RenderUrl('users/update#tab_users');

        if ($this->id_profile_type == PROFILE_SUPER_ADMINISTRATEUR) {

            unset($twig->context['hidden']);

            $twig->context['accounts'] = [
                'client_account_update' => [
                    'type' => 'select',
                    'label' => Strings::LABEL_0016,
                    'data' => $this->obj_Account->get_list_client(),
                    'selection' => $this->obj_Account->get_id_client_account(),
                    'attributes' => [
                        'onchange' => "ajax_function('" . BASE_WWW . "', '" . AJAX_CONTROLLER . "', ajax_refresh_client_linked_list_update);",
                    ],
                ],
            ];
        } else {
            $twig->context['hidden'] = [
                'client_account_update' => $this->obj_Account->get_id_client_account(),
            ];
        }

        $data = $this->get_user_data($this->id_user, $this->obj_Account->get_db_name());
        $twig->context['user'] = [
            'user_name_update' => [
                'type' => 'select',
                'label' => Strings::LABEL_0019,
                'data' => $this->get_all_users_name(),
                'selection' => $data[0][0],
                'attributes' => [
                    'onchange' => "ajax_function('" . BASE_WWW . "', '" . AJAX_CONTROLLER . "', ajax_refresh_user_form);",
                ],
            ],
            'user_firstname_update' => [
                'label' => Strings::LABEL_0042,
                'data' => $data[0][2],
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_spousename_update' => [
                'label' => Strings::LABEL_0043,
                'data' => $data[0][3],
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_email_update' => [
                'label' => Strings::LABEL_0046,
                'data' => $data[0][5],
                'attributes' => [
                    'size' => 35,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkEmail(this);',
                ],
            ],
            'user_matricule_update' => [
                'label' => Strings::LABEL_0044,
                'data' => $data[0][4],
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_function_update' => [
                'label' => Strings::LABEL_0045,
                'data' => $data[0][10],
                'attributes' => [
                    'size' => 25,
                    'maxlength' => 255,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                ],
            ],
            'user_profile_update' => [
                'type' => 'select',
                'label' => Strings::LABEL_0048,
                'data' => $this->get_list_profile(),
                'selection' => $data[0][13],
            ],
            'user_node_update' => [
                'type' => 'select',
                'label' => Strings::LABEL_0050,
                'data' => $this->obj_Account->obj_Corporate->get_list_node(),
                'selection' => $data[0][7],
            ],
            'user_date_start_contract_update' => [
                'id' => 'datepicker_user_date_start_contract_update',
                'label' => Strings::LABEL_0051,
                'data' => strcmp($data[0][11], "00/00/0000") === 0 ? NULL : $data[0][11],
                'attributes' => [
                    'size' => 11,
                    'maxlength' => 10,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkDate(this, false);',
                ],
            ],
            'user_date_end_contract_update' => [
                'id' => 'datepicker_user_date_end_contract_update',
                'label' => Strings::LABEL_0075,
                'data' => strcmp($data[0][12], "00/00/0000") === 0 ? NULL : $data[0][12],
                'attributes' => [
                    'size' => 11,
                    'maxlength' => 10,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkDate(this, false);',
                ],
            ],
        ];

        $data_login = $this->get_id_pwd_user($data[0][0]);
        $twig->context['credentials'] = [
            'login_update' => [
                'label' => Strings::LABEL_0005,
                'data' => $data_login[0][0],
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'autocomplete' => AUTOCOMPLETE,
                    'onblur' => 'checkLogin(this);',
                ],
            ],
            'pwd_update' => [
                'type' => 'password',
                'label' => Strings::LABEL_0006,
                'data' => $data_login[0][1],
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'onblur' => "checkPasswordEx(this,document.getElementById('pwd_update_bis'));",
                ],
            ],
            NULL,
            'pwd_update_bis' => [
                'type' => 'password',
                'label' => Strings::LABEL_0076,
                'data' => $data_login[0][1],
                'attributes' => [
                    'size' => 20,
                    'maxlength' => 20,
                    'required' => true,
                    'onblur' => "checkPasswordEx(this,document.getElementById('pwd_update'));",
                ],
            ],
        ];

        $strManagerFirstName = NULL;
        $strManagerProfile = NULL;

        $data_manager = $this->get_list_manager();
        //petit parsing pour remplir les champs prénom et profil du manager du collaborateur en cours d'affichage
        for ($inc = 0, $stop = (count($data_manager) - 1); $inc < $stop; $inc++) {
            if ($data_manager[$inc][0] == $data[0][6]) {
                $strManagerFirstName = $data_manager[$inc][2];
                $strManagerProfile = $data_manager[$inc][3];
            }
        }

        $twig->context['manager'] = [
            'user_manager_name_update' => [
                'type' => 'select',
                'label' => Strings::LABEL_0019,
                'data' => $data_manager,
                'selection' => $data[0][6],
                'attributes' => [
                    'onchange' => "ajax_function('" . BASE_WWW . "', '" . AJAX_CONTROLLER . "', ajax_refresh_manager_form);",
                ],
            ],
            'user_manager_firstname_update' => [
                'label' => Strings::LABEL_0042,
                'data' => $strManagerFirstName,
                'attributes' => [
                    'size' => 25,
                    'readonly' => true,
                ],
            ],
            'user_manager_profile_update' => [
                'label' => Strings::LABEL_0048,
                'data' => $strManagerProfile,
                'attributes' => [
                    'size' => 25,
                    'readonly' => true,
                ],
            ],
        ];

        $twig->context['Delete'] = [
            'name' => 'user_delete',
            'action' => RenderUrl('users/delete#tab_users'),
            'hidden' => [
                'client_account_del' => $this->obj_Account->get_id_client_account(),
                'id_user_del' => $data[0][0],
            ],
        ];

        $twig->display('forms/user/update');

        /*
         * TODO: twig that!
         */
        gui_alert_dialog('dialog_user_del', Strings::MESSAGE_0023);
    }

//============================================================================
// show_tab_users()
//============================================================================
    function show_tab_users($twig, $model) {
        echo gui_div_tag_open("tab_users");
        echo gui_div_tag_open("accordion_user");

        echo gui_div_tag_open();
        echo "<h3><a href=\"#\">" . Strings::LABEL_0047 . "</a></h3>";
        echo gui_div_tag_open();

        $this->Details($twig);

        echo gui_div_tag_close();
        echo gui_div_tag_close();

        if (in_array($this->id_profile_type, [ PROFILE_SUPER_ADMINISTRATEUR, PROFILE_ADMINISTRATEUR])) {
            echo gui_div_tag_open();
            echo "\n			<h3><a href=\"#\">" . Strings::LABEL_0053 . "</a></h3>";
            echo gui_div_tag_open();

            $this->Create($twig);

            echo gui_div_tag_close();
            echo gui_div_tag_close();

            echo gui_div_tag_open();
            echo "\n			<h3><a href=\"#\">" . Strings::LABEL_0211 . "</a></h3>";
            echo gui_div_tag_open();

            $this->Bulk($twig, $model);

            echo gui_div_tag_close();
            echo gui_div_tag_close();

            echo gui_div_tag_open();
            echo "\n			<h3><a href=\"#\">" . Strings::LABEL_0052 . "</a></h3>";
            echo gui_div_tag_open();

            $this->Update($twig);

            echo gui_div_tag_close();
            echo gui_div_tag_close();
        }

        echo gui_div_tag_close();
        echo gui_div_tag_close();
    }

//============================================================================
// get_list_node()
//============================================================================
    public function get_list_node($param_db_name = NULL) {
        /*
         * Obtient tous les noeuds.
         */
        global $REQUEST_019;
        return db_request_select($REQUEST_019, NULL, ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name);
    }

    public function get_node_by_name($name, $nodes) {
        foreach ($nodes as $node)
            if ($name === $node['designation'])
                return $node;
    }

//============================================================================
// create_profile()
//============================================================================
    public function create_profile($tab_arg) {
        GLOBAL $REQUEST_016, $REQUEST_015, $MESSAGE_0013;

        $dbName = $this->obj_Account->get_db_name();
        $tab_arg_tmp = [
            ':designation' => $tab_arg[':designation'],
            ':id_profil' => -1,
        ];

// On vérifie que la désignation du profil n'exista pas déjà
        $data = db_request_select($REQUEST_016, $tab_arg_tmp, $dbName);

        if ($data[0][0] == 0)
            db_request_insert($REQUEST_015, $tab_arg, $dbName);
        else
            throw new Exception($MESSAGE_0013);
    }

//============================================================================
// update_profile()
//============================================================================
    public function update_profile($tab_arg) {
        GLOBAL $REQUEST_016, $REQUEST_013, $MESSAGE_0013;

        $dbName = $this->obj_Account->get_db_name();
        $tab_arg_tmp = [
            ':designation' => $tab_arg[':designation'],
            ':id_profil' => $tab_arg[':id_profil'],
        ];

        // On vérifie que la désignation du profil n'exista pas déjà
        $data = db_request_select($REQUEST_016, $tab_arg_tmp, $dbName);

        if ($data[0][0] == 0)
            db_request_update($REQUEST_013, $tab_arg, $this->obj_Account->get_db_name());
        else
            throw new Exception($MESSAGE_0013);
    }

//============================================================================
// delete_profile
//============================================================================
    public function delete_profile($tab_arg) {
        GLOBAL $REQUEST_014, $REQUEST_048, $MESSAGE_0011;

        $dbName = $this->obj_Account->get_db_name();

//on doit vérifier que ce profil n'est pas utiliser dans la base de données du client.
//************************
        $data = db_request_select($REQUEST_048, $tab_arg, $dbName);

        if ($data[0][0] == 0)
            db_request_delete($REQUEST_014, $tab_arg, $dbName);
        else
            throw new Exception($MESSAGE_0011);
    }

//============================================================================
// get_list_profile()
// récupère la liste des profils
//============================================================================
    public function get_list_profile($param_db_name = NULL) {
        /*
         * Le super administrateur obtient tous les profils.
         * Les autres profils obtiennent tous les profils
         * exceptés les profils de type super administrateur.
         */
        global $REQUEST_012, $REQUEST_031;
        if ($this->id_profile_type == PROFILE_SUPER_ADMINISTRATEUR)
            return db_request_select($REQUEST_012, NULL, ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name);
        else
            return db_request_select($REQUEST_031, NULL, ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name);
    }

    public function get_profile_by_name($name, $profiles) {
        foreach ($profiles as $profile)
            if ($name === $profile['designation'])
                return $profile;
    }

//============================================================================
// get_list_profil_type()
//	récupère la liste des types de profil
//============================================================================
    public function get_list_profil_type($param_db_name = NULL) {
        GLOBAL $REQUEST_046, $REQUEST_047;
        try {
            $data = NULL;
//Si c un super administrateur il peut tout afficher comme type de profil
            if ($this->id_profile_type == PROFILE_SUPER_ADMINISTRATEUR)
                $data = db_request_select($REQUEST_046, NULL, ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name);
            else
                $data = db_request_select($REQUEST_047, NULL, ($param_db_name == NULL) ? $this->obj_Account->get_db_name() : $param_db_name);
            return $data;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

//============================================================================
// show_list_profile()
//============================================================================
    public function show_list_profile() {
        GLOBAL $LABEL_0028, $LABEL_0040, $LABEL_0130,
        $MESSAGE_9001,
        $ICON_VALIDATION, $ICON_DELETE, $ICON_ADD;

        $data = $this->get_list_profile();
        $dataProfil = $this->get_list_profil_type();
        ?>
        <div id="profiles" class="table">

            <div class="tr">
                <span class="head td_data_bold"><?= Strings::LABEL_0017 ?></span>
                <span class="head td_data_bold"><?= $LABEL_0130 ?></span>
                <span class="head td_data_bold"><?= $LABEL_0028 ?></span>
            </div>
            <?php for ($inc = 0, $stop = (count($data) - 1); $inc < $stop; $inc++) { ?>
                <form name="profil_update_<?= $inc ?>" action="<?= RenderUrl('profiles/update?profile=list') ?>" method='post' class="tr <?= ($inc % 2 == 0 ? 'tr_ligne_2' : 'tr_ligne_1') ?>">
                    <?= gui_form_input_hidden_field("id_profil", $data[$inc][0]) ?>
                    <span class="td">
                        <?= gui_form_input_text_field("designation", $data[$inc][1], 50, 255, "designation", true, false) ?>
                    </span>
                    <span class="td">
                        <?php
                        /* Les 5 premiers profils sont ceux d'origine
                         * et ne doivent pas être réaffectés.
                         */
                        $disabled = in_array($data[$inc][0], [1, 2, 3, 4, 5]);

                        if ($disabled) {
                            echo gui_form_input_hidden_field("id_profil_type", $data[$inc][2]);
                        }
                        echo gui_form_select_field("id_profil_type" . ($disabled ? '_disabled' : NULL), "id_profil_type" . ($disabled ? '_disabled' : NULL), $dataProfil, $data[$inc][2], $disabled, "", 0);
                        ?>
                    </span>
                    <span class="td">
                        <?php
                        echo gui_jqueryui_ul_open();
                        echo gui_jqueryui_li_icon($ICON_VALIDATION, "onclick=\"window.profile.update(" . $inc . ");\"");
                        echo gui_jqueryui_li_icon($ICON_DELETE, "onclick=\"window.profile.delete(" . $inc . ");\"");
                        echo gui_jqueryui_ul_close();
                        ?>
                    </span>
                </form>
            <?php } ?>
            <form name="profil_creation" action="<?= RenderUrl('profiles/create?profile=list') ?>" method='post' class="tr <?= ($inc % 2 == 0 ? 'tr_ligne_2' : 'tr_ligne_1') ?>">
                <span class="td">
                    <?= gui_form_input_text_field("new_designation", "", 50, 255, "new_designation", true, false) ?>
                </span>
                <span class="td">
                    <?= gui_form_select_field("new_id_profil_type", "new_id_profil_type", $dataProfil, NULL, false, "", 0) ?>
                </span>
                <span class="td">
                    <?php
                    echo gui_jqueryui_ul_open();
                    echo gui_jqueryui_li_icon($ICON_ADD, "onclick=\"window.profile.create();\"");
                    echo gui_jqueryui_ul_close();
                    ?>
                </span>
            </form>
        </div>
        <?php
        echo gui_info_message($MESSAGE_9001);
    }

}
